<?php


namespace App\Http\Controllers\Admin;


use App\Model\Admin;
use App\Model\RulesGroup;
use App\Model\RulesGroupDetail;
use App\Service\Search\Search;
use App\Tool\Json;
use Illuminate\Support\Facades\DB;



class AdminController extends AuthCheckController
{

    function admin_list()
    {


        $list = Admin::with('role')->orderBy('id', 'desc');


        \App\Tool\Search::searchList($list,request()->input('search','[]'));


        return Json::code(1, 'success', paginate($list, request()->input('p')));

    }

    function admin_update()
    {


        $id = request()->input('id', 0);


        $post = request()->input();


        try {
            DB::beginTransaction();
            $autoId = 0;

            if ($id) {


                if (isset($post['username'])) unset($post['username']);

                $admin = Admin::find($id);

                if(!$admin) throw new \Exception('管理员id不存在');

                $admin->fill($post)->save();


                $autoId = $id;

            } else {


                $admin = new Admin();

                $admin->fill($post)->save();

                $autoId = $admin->id;

            }

            if($admin->username=='root'&&$post['group_id']!=0) throw new \Exception('初始管理员无法修改角色');


            RulesGroupDetail::updateOrCreate(['uid' => $autoId], ['uid' => $autoId, 'rules_group_id' => $post['group_id']]);

            DB::commit();

            return Json::code(1, 'success');

        } catch (\Exception $exception) {

            DB::rollBack();

            return Json::code(2,$exception->getMessage());


        }


    }

    /**
     * 获取管理员信息
     * Create by Peter
     * 2019/08/21 17:01:41
     * Email:904801074@qq.com
     * @return false|string
     */
    function admin_info()
    {

        $id = request()->input('id');

        $info = Admin::leftJoin('rules_group_detail','admins.id','=','rules_group_detail.uid')
            ->select(DB::raw('admins.*,rules_group_detail.rules_group_id group_id'))
            ->find($id);



        return Json::code(1, 'success', $info);

    }


    /**
     * Create by Peter
     * 2019/08/22 17:04:01
     * Email:904801074@qq.com
     * @param $id
     * @return false|string
     */
    function admin_delete(int $id)
    {

        try {

            Admin::destroy($id);

            return Json::code(1, 'success', $id);
        }catch (\Exception $exception){

            return  Json::code(2,$exception->getMessage());

        }
    }

    function getAllGroupName()
    {

        $list = RulesGroup::all(['id', 'title']);

        return Json::code(1, 'success', $list);

    }

}
